package com.example.multitouchtest;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class DrawView extends View implements OnTouchListener {
	Paint paint = new Paint();
	Paint leftSidePaint = new Paint();
	Paint rightSidePaint = new Paint();
	int leftWidth = 300;

	public DrawView(Context context) {
		super(context);
		setFocusable(true);
		setFocusableInTouchMode(true);
		this.setOnTouchListener(this);

		paint.setAntiAlias(true);
		paint.setColor(Color.rgb((int) (Math.random() * 256),
				(int) (Math.random() * 256), (int) (Math.random() * 256)));
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeJoin(Paint.Join.ROUND);
		paint.setStrokeWidth(10f);
		leftSidePaint.setColor(Color.BLACK);
		rightSidePaint.setColor(Color.BLACK);

	}

	@Override
	public void onDraw(Canvas canvas) {
		canvas.drawRect(0, 0, 300, canvas.getHeight(), leftSidePaint);
		canvas.drawRect(leftWidth, 0, leftWidth + 300, canvas.getHeight(),
				rightSidePaint);
	}

	public boolean onTouch(View view, MotionEvent event) {
		 super.onTouchEvent(event);
		Log.d("MultiTouch", "Pointer count: " + event.getPointerCount());
		if (event.getPointerCount() == 1) {
			
			handleSingleTouch(event);
		} else {
			handleMultiTouch(event);
		}

		invalidate();

		return true;
	}

	private void handleMultiTouch(MotionEvent event) {
		int x = (int) event.getX();
		int x2 = (int) event.getX(1);

		if (x < leftWidth || x2 < leftWidth) {
			leftSidePaint.setColor(Color.RED);
		} else {
			leftSidePaint.setColor(Color.BLACK);
		}

		if (x > leftWidth || x2 > leftWidth) {
			Log.d("Multitouch", "SET RED");
			rightSidePaint.setColor(Color.RED);
		} else {
			rightSidePaint.setColor(Color.BLACK);
		}
		if (event.getAction() == MotionEvent.ACTION_UP
				|| event.getAction() == MotionEvent.ACTION_POINTER_UP) {
			if (x > leftWidth || x2 > leftWidth) {
				rightSidePaint.setColor(Color.BLACK);
			}
			if (x < leftWidth || x2 < leftWidth) {
				leftSidePaint.setColor(Color.BLACK);
			}

		}

	}

	private void handleSingleTouch(MotionEvent event) {
		int x = (int) event.getX();

		if (x < leftWidth) {
			leftSidePaint.setColor(Color.RED);
		} else {
			leftSidePaint.setColor(Color.BLACK);
		}

		if (x > leftWidth) {
			Log.d("Multitouch", "SET RED");
			rightSidePaint.setColor(Color.RED);
		} else {
			rightSidePaint.setColor(Color.BLACK);
		}
		if (event.getAction() == MotionEvent.ACTION_UP) {
			if (x > leftWidth) {
				rightSidePaint.setColor(Color.BLACK);
			}
			if (x < leftWidth) {
				leftSidePaint.setColor(Color.BLACK);
			}

		}

	}
}